package cn.arikeky.org.service.impl;

import cn.arikeky.basic.config.BussinessException;
import cn.arikeky.basic.query.BaseQuery;
import cn.arikeky.basic.util.BaiduAuditUtils;
import cn.arikeky.basic.util.PageList;
import cn.arikeky.org.domain.Employee;
import cn.arikeky.org.domain.Shop;
import cn.arikeky.org.domain.ShopAuditLog;
import cn.arikeky.org.enu.ShopStateEum;
import cn.arikeky.org.mapper.EmployeeMapper;
import cn.arikeky.org.mapper.ShopAuditLogMapper;
import cn.arikeky.org.mapper.ShopMapper;
import cn.arikeky.org.service.IEmployeeService;
import cn.arikeky.org.service.IShopService;
import cn.arikeky.basic.service.impl.BaseServiceImpl;
import cn.arikeky.org.vo.ShopEchartsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author arikeky
 * @since 2022-10-15
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private EmployeeServiceImpl employeeService;


    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        PageList<Shop> shopPageList = super.queryByPage(query);
        // 这块是5条数据
        List<Shop> rows = shopPageList.getRows();
        if (CollectionUtils.isEmpty(rows)){
            return new PageList<>();
        }
        // 把shopId取出来
        List<Long> shopIds = rows.stream().map(Shop::getId).collect(Collectors.toList());
        // 根据shopId查询日志
        List<ShopAuditLog> logList = shopAuditLogMapper.findByShopIds(shopIds);
        // 组装 将每个shop对象下的auditLogs 组装起来
        // key 店铺id value 日志表集合

//        Map<Long, List<ShopAuditLog>> logMap = logList.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        Map<Long, List<ShopAuditLog>> logMap = new HashMap<>();
        for (ShopAuditLog log : logList) {
            List<ShopAuditLog> shopAuditLogs = logMap.get(log.getShopId());
            if (CollectionUtils.isEmpty(shopAuditLogs)){
                shopAuditLogs = new ArrayList<>();
            }
            shopAuditLogs.add(log);
            logMap.put(log.getShopId(),shopAuditLogs);
        }

        rows.forEach(row->{
            row.setAuditLogs(logMap.get(row.getId()));
        });

        return shopPageList;
    }

    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        // 判断前端传入参数是否为空
        // 判断名字
        if (StringUtils.isBlank(shop.getName())){
            // 手动抛异常
            throw new BussinessException("店铺名称不能为空！请重新填写");
        }
        // 判断名电话
        if (StringUtils.isEmpty(shop.getTel())){
            // 手动抛异常
            throw new BussinessException("电话号码不能为空！请重新填写");
        }
        // 判断地址
        if (StringUtils.isEmpty(shop.getAddress())){
            // 手动抛异常
            throw new BussinessException("店铺地址不能为空！请重新填写");
        }
        // 判断两次密码是否一致

        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不一致！请重新填写");
        }

        // 百度AI判断
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("名称不合规");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺logo不合规");
        }
        // 判断申请入住的店铺是否已经存在,用店铺名称判断
        Shop loadShop = shopMapper.loadByName(shop.getName());
        if (null != loadShop){
            throw new BussinessException("店铺名称已存在！请重新填写");
        }
        // 判断管理员是否已经管理店铺

        Employee loadEmp = employeeMapper.loadByUserName(admin.getUsername());
        if (null != loadEmp && null != loadEmp.getShopId()){
            Shop shopById = shopMapper.findById(loadEmp.getShopId());
            if (shopById.getAdminId().equals(loadEmp.getId())){
                throw new BussinessException("当前管理员已经管理店铺！请重新填写");
            }
        }
        // 当没有管理员的时候进行创建
        shopMapper.add(shop);
        if (null == loadEmp) {
            loadEmp = admin;
            employeeService.add(loadEmp);
        }
        // 修改shopId
        loadEmp.setShopId(shop.getId());
        employeeMapper.update(loadEmp);
        // 修改 adminId
        Shop uptshop = new Shop();
        uptshop.setId(shop.getId());
        uptshop.setAdminId(loadEmp.getId());
        shopMapper.update(uptshop);
    }

    // 审核日志记录
    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
        // 判断参数
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空");
        }
        // 修改店铺状态为审核通过
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 添加店铺日志
        shopAuditLog.setState(1);
        shopAuditLog.setAuditId(11L);
        shopAuditLogMapper.add(shopAuditLog);
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("864753517@qq.com");
            helper.setSubject("宠物之家入住审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>恭喜您已经通过审核，点击下方链接即可激活</h1><br><hr><br>"+"http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
            // 4.添加附件
            helper.addAttachment("好东西.jpg",new File("D:\\资料\\学习资料\\4.jpg"));
            // 5.设置收件人
            helper.setTo("864753517@qq.com");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("发送邮件失败");
        }
        // 6.发送邮件
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
        // 判断参数
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空");
        }
        // 修改店铺状态为审核通过
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        // 添加店铺日志
        shopAuditLog.setState(-1);
        shopAuditLog.setAuditId(11L);
        shopAuditLogMapper.add(shopAuditLog);
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("864753517@qq.com");
            helper.setSubject("宠物之家入住审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>您的申请已被驳回，点击下方链接查看原因或重新提交入住申请</h1><br><hr><br>"+"http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId(),true);
            // 5.设置收件人
            helper.setTo("864753517@qq.com");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("发送邮件失败");
        }
        // 6.发送邮件
        javaMailSender.send(mimeMessage);
    }

//    @Override
//    public void reject(Long id) {
//        Shop shop = new Shop();
//        shop.setId(id);
//        shop.setState(0);
//        shopMapper.update(shop);
//    }

    @Override
    public void again(Shop shop) {
        // 判断名字
        if (StringUtils.isBlank(shop.getName())){
            // 手动抛异常
            throw new BussinessException("店铺名称不能为空！请重新填写");
        }
        // 判断名电话
        if (StringUtils.isEmpty(shop.getTel())){
            // 手动抛异常
            throw new BussinessException("电话号码不能为空！请重新填写");
        }
        // 判断地址
        if (StringUtils.isEmpty(shop.getAddress())){
            // 手动抛异常
            throw new BussinessException("店铺地址不能为空！请重新填写");
        }
        // 百度AI判断
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("名称不合规");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺logo不合规");
        }
        shop.setId(shop.getId());
        shop.setName(shop.getName());
        shop.setTel(shop.getTel());
        shop.setAddress(shop.getAddress());
        shop.setState(0);
        shop.setLogo(shop.getLogo());
        shopMapper.update(shop);
    }

    @Override
    public Map<String, Object> echarts() {
        Map<String,Object> resurl = new HashMap<>();
         List<ShopEchartsVo> vo = shopMapper.echarts();

        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());

        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());

        List<String> realx = new ArrayList<>();
        for (Integer xTemp : x) {
            String stateByCode = ShopStateEum.getNameByCode(xTemp);
            realx.add(stateByCode);
        }

        resurl.put("x",realx);
        resurl.put("y",y);
        return resurl;
    }

    @Override
    public Shop findByEmpId(Long id) {
        return shopMapper.findByEmpId(id);
    }

}
